import Request from 'luch-request'
import config from './config.js'
const request = new Request({
	baseURL: config.baseURL,
	timeout: 6000,
	header: {
		'Content-type': 'application/x-www-form-urlencoded',
	},
});
//请求拦截器
request.interceptors.request.use((config) => { // 可使用async await 做异步操作
	//auth true，hader添加参数。
	if (config.custom.auth) {

		config.header = {
			token: uni.getStorageSync('token')
		}

	}

	return config
}, config => { // 可使用async await 做异步操作
	return Promise.reject(config)
})

//响应拦截器
request.interceptors.response.use((response) => {
	console.log(response, 11)
	if (response.data.code === 1) {
		return response.data;
	} else if (response.data.code === 401) {
		showToast(response.data.msg);
		uni.showModal({
			title: '提示',
			content: '请重新登陆！',
			success: function(res) {
				if (res.confirm) {
					uni.reLaunch({
						url: '/pages/login/login'
					});
				}
			}
		});
		return Promise.reject();
	} else if (response.data.code === 0) {
		showToast(response.data.msg);
		return Promise.reject();
	} else {
		return Promise.reject(response);
	}

	return response
}, (response) => {
	showToast(response.data.msg);
	if (response.statusCode === 401) {
		uni.showModal({
			title: '提示',
			content: '请重新登陆！',
			success: function(res) {
				if (res.confirm) {
					uni.reLaunch({
						url: '/pages/login/login'
					});
				}
			}
		});
	} 
	return Promise.reject(response)
})

function showToast(title, icon = 'none', time = 2000) {
	uni.showToast({
		title: title,
		icon: icon,
		duration: time,
	});
}

export default request;
